import { useMenuStore } from '@/stores/menu'

// 权限指令
export const permission = {
  mounted(el, binding) {
    const { value } = binding
    const menuStore = useMenuStore()
    
    if (value) {
      let hasPermission = false
      
      if (Array.isArray(value)) {
        // 数组形式：检查是否有任意一个权限
        hasPermission = value.some(permission => menuStore.hasPermission(permission))
      } else if (typeof value === 'string') {
        // 字符串形式：检查单个权限
        hasPermission = menuStore.hasPermission(value)
      }
      
      if (!hasPermission) {
        // 没有权限则隐藏元素
        el.style.display = 'none'
        // 或者移除元素
        // el.parentNode && el.parentNode.removeChild(el)
      }
    }
  },
  
  updated(el, binding) {
    // 权限更新时重新检查
    const { value } = binding
    const menuStore = useMenuStore()
    
    if (value) {
      let hasPermission = false
      
      if (Array.isArray(value)) {
        hasPermission = value.some(permission => menuStore.hasPermission(permission))
      } else if (typeof value === 'string') {
        hasPermission = menuStore.hasPermission(value)
      }
      
      if (hasPermission) {
        el.style.display = ''
      } else {
        el.style.display = 'none'
      }
    }
  }
}

// 角色指令
export const role = {
  mounted(el, binding) {
    const { value } = binding
    const menuStore = useMenuStore()
    
    if (value) {
      let hasRole = false
      
      if (Array.isArray(value)) {
        // 数组形式：检查是否有任意一个角色
        hasRole = value.some(role => menuStore.hasRole(role))
      } else if (typeof value === 'string') {
        // 字符串形式：检查单个角色
        hasRole = menuStore.hasRole(value)
      }
      
      if (!hasRole) {
        el.style.display = 'none'
      }
    }
  },
  
  updated(el, binding) {
    const { value } = binding
    const menuStore = useMenuStore()
    
    if (value) {
      let hasRole = false
      
      if (Array.isArray(value)) {
        hasRole = value.some(role => menuStore.hasRole(role))
      } else if (typeof value === 'string') {
        hasRole = menuStore.hasRole(value)
      }
      
      if (hasRole) {
        el.style.display = ''
      } else {
        el.style.display = 'none'
      }
    }
  }
}